package com.cloud.school.app.config.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.io.InputStreamSource;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @ClassName ControllerAspect
 * @Description TODO
 * @Author 36297
 * @Date 2019/1/14 20:39
 * @Version 1.0
 */
@Slf4j
@Component
@Aspect
public class ControllerAspect {

    @Pointcut("within(com.cloud.school.app.controller.*) && @annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void loggingPointcut() {
    }

    @Around("loggingPointcut()")
    protected Object aroudAdivce(ProceedingJoinPoint jp) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String reqParam = StringUtils.rightPad(request.getMethod(), 5, ' ') + " " + request.getServletPath();
        if (log.isInfoEnabled()) {
            List<Class> classes = Lists.newArrayList(File.class, InputStream.class, InputStreamSource.class, byte[].class, HttpServletRequest.class, HttpServletResponse.class);//所有过滤参数
            List args = Stream.of(jp.getArgs()).filter(arg -> classes.stream().noneMatch(testClass -> testClass.isInstance(arg))).collect(Collectors.toList());
            String argsString = JSON.toJSONString(args);
            log.info("REQUEST BEGIN.......: {} , args={} ", reqParam, argsString);
        }
        long startTime = System.currentTimeMillis();
        Object rt = jp.proceed();// 方法返回参数
        long cost = System.currentTimeMillis() - startTime;
        if (log.isInfoEnabled()) {
            String result = JSON.toJSONString(rt, SerializerFeature.DisableCircularReferenceDetect);
            log.info("REQUEST END  [cost={}] : {} , result = {}", StringUtils.leftPad(cost + "", 4), reqParam, result);
        }
        return rt;
    }
}
